# -*- coding:utf-8 -*
import os
import zipfile
import rarfile
from win32com import client as wc
from time import sleep
from pathlib import Path
import shutil
import threading
from docx import Document, ImagePart
import re
from loguru import logger
import socket

logger.add("tool.log", retention="3 days")

from zipfile import ZipFile


def support_gbk(zip_file: ZipFile):
    name_to_info = zip_file.NameToInfo
    # copy map first
    for name, info in name_to_info.copy().items():
        real_name = name.encode('cp437').decode('gbk')
        if real_name != name:
            info.filename = real_name
            del name_to_info[name]
            name_to_info[real_name] = info
    return zip_file


def detect_port(port):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.connect(('127.0.0.1', int(port)))
        s.shutdown(2)
        return True
    except:
        return False


@logger.catch
def doc_to_docx(file_path):
    logger.info("doc文件转docx:[{}]".format(file_path))
    word = wc.Dispatch('Word.Application')
    doc = word.Documents.Open(file_path)
    docx_path = file_path.split(".doc")[0] + ".docx"
    doc.SaveAs(docx_path, 12)
    doc.Close()
    word.Quit()
    sleep(2)


class DirCheck:
    def __init__(self, dir):
        self.dir = dir

    @logger.catch
    def list(self, progressbar, load_pop):
        logger.info("目录检查：{}", self.dir)
        files_arr = []
        for root, dirs, files in os.walk(self.dir):
            for file in files:
                file_path = os.path.join(root, file).replace("/", "\\")
                # print(file_path)
                if file.endswith('zip'):
                    print("")
                    self.un_zip(file_path)
                elif file.endswith('rar'):
                    self.un_rar(file_path)
                elif file.endswith('doc'):
                    doc_to_docx(file_path)
                    self.bak(file_path)
        sleep(2)
        for i in range(50, 100):
            progressbar["value"] = i + 1
            load_pop.update()
            sleep(0.001)
        load_pop.destroy()
        for root, dirs, files in os.walk(self.dir):
            for file in files:
                file_path = os.path.join(root, file).replace("/", "\\")
                files_arr.append(file_path)
        return self.toDict(files_arr)

    def bak(self, file):
        work_path = os.path.join(os.path.abspath("."), "bak")

        fpath, fname = os.path.split(file)  # 分离文件名和路径
        if not os.path.exists(work_path):
            os.makedirs(work_path)  # 创建路径
        shutil.move(file, os.path.join(work_path, fname))  # 移动文件
        print("move %s -> %s" % (file, os.path.join(work_path, fname)))

    @staticmethod
    def clear_bak():
        work_path = os.path.join(os.path.abspath("."), "bak")
        if os.path.exists(work_path):
            shutil.rmtree(work_path)

    @staticmethod
    def clear_cache():
        cache_path = os.path.join(os.path.abspath("."), "kkFileView-4.0.0/file/")
        print(cache_path)
        if os.path.exists(cache_path):
            shutil.rmtree(cache_path)
            os.makedirs(cache_path)
        # os.remove(os.path.join(os.path.abspath("."), "kkFileView-4.0.0/log/kkFileView.log"))

    def toDict(self, files):
        num = 1
        file_dict = {}
        for item in files:
            file_dict[num] = item
            num = num + 1
        return file_dict

    @logger.catch
    def un_zip(self, zippath):
        destpath = os.path.dirname(zippath)
        with support_gbk(zipfile.ZipFile(zippath, 'r')) as fzip:
            fzip.extractall(destpath)
        # os.rename(zippath, zippath + ".bak")
        self.bak(zippath)

    @logger.catch
    def un_rar(self, rarpath):
        destpath = os.path.dirname(rarpath)
        rarobj = rarfile.RarFile(rarpath)
        rarobj.extractall(destpath)
        # os.rename(rarpath, rarpath + ".bak")
        self.bak(rarpath)


class DocxTool:
    def __init__(self, document: Document):
        self.doc = document
        self.images = []
        self.images_num = 0

    @logger.catch
    def get_all_image(self):
        dict_rel = self.doc.part._rels
        dict_img = {}
        for rel in dict_rel:
            rel = dict_rel[rel]
            # print("rel", rel.target_ref)
            if "image" in rel.target_ref:
                img_name = re.findall("/(.*)", rel.target_ref)[0]
                num = img_name.replace(".png", "").replace(".jpg", "") \
                    .replace(".jpeg", "").replace("image", "")
                # print(num)
                dict_img[num] = rel.target_part
        dict_img = dict(sorted(dict_img.items(), key=lambda x: x[0]))
        for val in dict_img.values():
            self.images.append(val)
        self.images_num = len(self.images)
